$(function(){
	var changeTime = function(time) {
		var date = new Date(time);
		var year = date.getFullYear();
		var month = date.getMonth()+1<10?('0'+(date.getMonth()+1)):date.getMonth()+1;
		var day = date.getDate() < 10 ? '0'+date.getDate() : date.getDate();
		var hour = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
		var min = date.getMinutes() < 10 ? '0'+date.getMinutes():date.getMinutes();

		return year+'-'+month+'-'+day+' '+hour+':'+min;
	}

	var member = {
		getList: function() {
			$.ajax({
			    url: wsCommon.host + '/api/members/center',
			    dataType: wsCommon.jsonType,
			    success: function(res) {
					if(res.code == 1) {
						if(res.result) {
							var data = res.data;

							$('[data-role="username"]').html(data.username);
							$('[data-role="vip"]').html(data.memberLevel);
							$('[data-role="point"]').html(data.needPoint);
							$('[data-role="nextVip"]').html(data.nextMemberLevel);

							member.upgrade(data.nextMemberLevel, data.upgradePoint, data.nextLvExpireTime);

							if(data.canUpgrade) {
								$('[data-role="canUpgrade"]').show();
								$('[data-role="nextLevels"]').html(data.nextMemberLevel);
								$('[data-role="discount"]').html(data.nextLevelDisCount*10);
								if(data.expireTime != null) $('[data-role="deadline"]').html('到期时间：'+data.expireTime)
							} else {
								$('[data-role="cannotUpgrade"]').show();
								if(data.hasNextLevel) {

								} else {
									$('[data-role="cannotUpgrades"]').show();
									$('[data-role="cannotUpgrade"]').hide();
									$('[data-role="cannotUpgradediscount"]').html(data.currentDisCount * 10);
								}
								if(data.expireTime != null) $('[data-role="deadline"]').html('到期时间：'+data.expireTime)
							}

							$('[data-role="allPoint"]').html(data.point);
							$('[data-role="yue"]').html(data.advance);
							$('[data-role="youhui"]').html(data.countForCoupon);

							$('#waitPay').html(data.countForPay);
							$('#waitReceive').html(data.countForShip);
							$('#waitPick').html(data.countForComment);
							$('#productCount').html(data.countForReturn);

							// 订单
							var orderPager = data.orderPager;
							var orderPagerTpl = '';
							if(orderPager.list.length > 0) {
								$.each(orderPager.list, function(index, item) {
									if(index > 5) return;
									var payStatusTpl = '';
									if(item.paymentType != 2 && item.paymentType != 1 && item.status != 'dead' && item.status != 'finish' && item.payStatus != 1) {
										payStatusTpl = '<a href="javascript:;" class="btn btn-import" data-role="tocart3" data-orderid="'+item.orderId+'"><span><span>去付款</span></span></a>';
									}
									var changePayTpl = '';
									if(item.status != 'dead' && item.status != 'finish' && item.payStatus != 1) {
										changePayTpl = '<a href="javascript:;" class="btn btn-simple" data-role="tocart3" data-orderid="'+item.orderId+'"><span><span>修改支付方式</span></span></a>';
									}
									var orderStatusTpl = '';
									if(item.status == 'active') {
										if(item.payStatus == 0) {
											orderStatusTpl = '未支付';
										} else if(item.payStatus == 1) {
											orderStatusTpl = '已支付';
										} else if(item.payStatus == 2) {
											orderStatusTpl = '已付款至到担保方';
										} else if(item.payStatus == 3) {
											orderStatusTpl = '部分付款';
										} else if(item.payStatus == 4) {
											orderStatusTpl = '部分退款';
										} else if(item.payStatus == 5) {
											orderStatusTpl = '全额退款';
										}

									} else if(item.status == 'dead') {
										orderStatusTpl = '已作废';
									} else if(item.status == 'finish') {
										orderStatusTpl = '已完成';
									}
									if(item.shipStatus == 1) {
										orderStatusTpl+= '(已发货)'
									}
									orderPagerTpl += '<tr>\
														<td class="order" width="28%"><a href="./member-orderdetail.html?orderId='+item.orderId+'">'+item.orderId+'</a><span class="handle action-view-goods">['+item.itemsList.length+'商品]</span></td>\
														<td class="price">¥'+item.finalAmount+'</td>\
														<td class="datetime">'+changeTime(item.createTime)+'</td>\
														<td class="status">'+orderStatusTpl+'</td>\
														<td class="payments">'+item.paymentName+'</td>\
														<td class="actions" valign="top" rowspan="2">'+payStatusTpl+'<i class="separator"></i>\
														   <a href="./member-orderdetail.html?orderId='+item.orderId+'">查看订单</a>\
														   <i class="separator"></i>\
														   <a href="javascript:;" data-role="buyagain" >再次购买</a>\
														   <i class="separator"></i>'+changePayTpl+'</td>\
													</tr>';
									orderPagerTpl += '<tr class="goods-row">\
													<td colspan="5">\
														<ul class="member-piclist">';
									$.each(item.itemsList, function(indexDir, itemDir) {
										orderPagerTpl += '<li class="goods-item" data-goodsid="'+itemDir.goodsId+'" data-productid="'+itemDir.productId+'" data-quantity="'+itemDir.nums+'">\
												   <div class="goods-pic" data-tips="'+itemDir.name+'">\
													   <a href="./info.html?goodsId='+itemDir.goodsId+'&catId='+itemDir.catId+'"><img src="'+itemDir.imageUrl+'" alt="'+itemDir.name+'"></a>\
												   </div>\
												</li>';
									})
									orderPagerTpl += '</ul>\
											</td>\
										</tr>';
								})
								$('[data-role="order"]').html(orderPagerTpl);
							} else {
								$('.member-mod-content').append('<p style="text-align: center;line-height: 80px;width: 100%;font-size: 16px;">暂无</p>');
							}


							// 收藏
							var favPager = data.favPager;
							var favPagerTpl = '';
							if(favPager.list.length > 0) {
								$.each(favPager.list, function(index, item) {
									if(index > 4) return;
									favPagerTpl += '<li class="goods-item">\
							                            <div class="goods-pic"><a href="./info.html?goodsId='+item.goodsId+'&catId='+item.catId+'" target="_blank"><img  src="'+item.imgUrl+'" alt="'+item.productName+'"></a></div>\
							                            <h3 class="goods-name"><a href="./info.html?goodsId='+item.goodsId+'&catId='+item.catId+'" target="_blank">'+item.productName+'</a></h3>\
							                            <div class="price">¥'+item.mktprice+'</div>\
							                        </li>';
								})
								favPagerTpl += '<li class="last"></li>';
								$('.member-goods-list').html(favPagerTpl);
							} else {
								$('.member-goods-list').append('<li style="text-align: center;line-height: 80px;width: 100%;font-size: 16px;letter-spacing:0;">暂无</li>');
							}

						} else {
							wsCommon.setCookie('go_back_link', window.location.href);
							window.location.href = './passport-login.html';
						}
					}
			    },
			    error: function() {
			        // console.log('接口返回失败');
			    }
			})
		},
		upgrade: function(nextMemberLevel, upgradePoint, nextLvExpireTime) {
			$(document).on('click', '[data-role="upgrade"]', function() {
				var result = window.confirm('您确定要升级为'+nextMemberLevel+'吗？\n将扣除'+upgradePoint+'积分\n有效期为'+nextLvExpireTime);
				if(result) {
					$.ajax({
						url: wsCommon.host + '/api/members/upgrade',
						dataType: wsCommon.jsonType,
						success: function(res) {
							if (res.code == 1) {
								iosOverlay({
									text: res.reason,
									duration: 1000,
									onhide: function() {
										window.location.reload();
									}
								});
							}
						},
						error: function() {

						}
					})
				}
			})
		},
		buyAgain: function() {
			$(document).on('click', '[data-role="buyagain"]', function() {
				var goodsitem = $(this).closest('tr').next('tr').find('.goods-item');
				var arr = [];
				iosOverlay({
					text: "正在跳转页面!",
					duration: 150000
				});

				$.each(goodsitem, function(index, item) {
					var obj = {};
					obj.goodsId = $(item).attr('data-goodsid');
					obj.productId = $(item).attr('data-productid');
					obj.quantity = $(item).attr('data-quantity');
					obj.objType = 'goods';
					arr.push(obj);
				})

				$.ajax({
	                url: wsCommon.host + '/api/cart/addGoodsBatch',
	                dataType: wsCommon.jsonType,
					data: {
						cartGoodsInfo:JSON.stringify(arr)
					},
	                success: function(res) {
						if (res.code == 1) {
							window.location.href = './cart1.html';
						}
					},
					error: function() {

					}
				})
			})
		},
		toPay: function() {
			$(document).on('click', '[data-role="tocart3"]', function() {
				var orderInfo = {
					orderId: $(this).attr('data-orderid')
				};

				wsCommon.setCookie('orderInfo', JSON.stringify(orderInfo));

				window.location.href = './cart3.html';
			})
		},
		init: function() {
			this.getList();
			this.buyAgain();
			this.toPay();
		}
	}

	member.init();
})
